﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using A2DFramework.AOPService.Core;
using A2DFramework.ContextService;
using A2DFramework.InstanceService;
using A2DFramework.ValidationService;

namespace A2DFramework.CommandBusService.MSMQCommandBus
{
    public class MSMQCommandBusImpl : ICommandBus
    {
        public TResult Send<TCmd, TResult>(TCmd cmd)
            where TCmd : BaseCommand
            where TResult : BaseCommandResult
        {
            ValidateCommand(cmd);

            CommandBusDistributer<TCmd, TResult> distributer = new CommandBusDistributer<TCmd, TResult>();
            distributer.SendRequest(cmd);
            TResult result=distributer.WaitResponse();
            return result;
        }

        public void ValidateCommand(object o)
        {
            List<BrokenRule> errors = o.IsValid();
            if (errors != null && errors.Count > 0)
            {
                CoreContext.Current.BrokenRulesContainer.AddBrokenRules(errors);
                throw new Exception(string.Format("命令存在非法参数[{0}]: {1}", o.GetType().Name, CoreContext.Current.BrokenRulesContainer.ToString()));
            }
        }

    }
}
